package com.alan.camunda.boot.controller;

import com.alan.camunda.boot.dto.CommentVO;
import com.alibaba.fastjson2.JSONObject;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import org.apache.commons.io.IOUtils;
import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.history.HistoricProcessInstance;
import org.camunda.bpm.engine.history.HistoricVariableInstance;
import org.camunda.bpm.engine.impl.persistence.entity.HistoricVariableInstanceEntity;
import org.camunda.bpm.engine.runtime.VariableInstance;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.Instant;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/variables")
public class VariablesController {
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private HistoryService historyService;
    @Resource
    private JdbcTemplate jdbcTemplate;


    @PostMapping("/setByInsId")
    public String setByInsId(String insId, @RequestBody Map<String, Object> variables) {
        if (variables != null && variables.size() > 0) {
            // 设置流程变量
            runtimeService.setVariables(insId, variables);
        }

        runtimeService.setVariable(insId, "myDate", new Date());

        CommentVO comment = new CommentVO();
        comment.setTaskId("t11");
        comment.setUserId("user1");
        comment.setCreateTime(new Date());
        comment.setComment("Hello World!");
        runtimeService.setVariable(insId, "comment", comment);

        JSONObject map = new JSONObject();
        map.put("f1", "111");
        map.put("f2", comment);
        map.put("f3", new Date());

        runtimeService.setVariable(insId, "myMap", map);

        return "success";
    }


    @GetMapping("/byInsIdRun")
    public String byInsIdRun(String insId) {
        List<VariableInstance> list =
                runtimeService.createVariableInstanceQuery().processInstanceIdIn(insId).list();

        JSONObject data = new JSONObject();
        for (VariableInstance item : list) {
            data.put(item.getName(), item.getValue());
        }
        return data.toJSONString();
    }

    @GetMapping("/byInsIdHistory")
    public String byInsIdHistory(String insId) {
        List<HistoricVariableInstance> list = historyService.createHistoricVariableInstanceQuery()
                .processInstanceId(insId).list();

        JSONObject data = new JSONObject();
        for (HistoricVariableInstance item : list) {
            data.put(item.getName(), item.getValue());
        }
        return data.toJSONString();
    }


    @SneakyThrows
    @GetMapping("/testMyRead")
    public String testMyRead() throws FileNotFoundException {
        RowMapper<HistoricVariableInstanceEntity> rowMapper = new BeanPropertyRowMapper<HistoricVariableInstanceEntity>(HistoricVariableInstanceEntity.class);
        String sql = """
                select
                    ID_ id,
                    PROC_DEF_KEY_ processDefinitionKey,
                    PROC_DEF_ID_ processDefinitionId,
                    ROOT_PROC_INST_ID_ rootProcessInstanceId,
                    PROC_INST_ID_ processInstanceId,
                    EXECUTION_ID_ executionId,
                    ACT_INST_ID_ activityInstanceId,
                    TENANT_ID_ tenantId,
                    CASE_DEF_KEY_ caseDefinitionKey,
                    CASE_DEF_ID_ caseDefinitionId,
                    CASE_INST_ID_ caseInstanceId,
                    CASE_EXECUTION_ID_ caseExecutionId,
                    TASK_ID_ taskId,
                    NAME_ name,
                    REV_ revision,
                    VAR_TYPE_ serializerName,
                    CREATE_TIME_ createTime,
                    BYTEARRAY_ID_ byteArrayId,
                    DOUBLE_ doubleValue,
                    TEXT_ textValue,
                    TEXT2_ textValue2,
                    LONG_ longValue,
                    STATE_ state,
                    REMOVAL_TIME_ removalTime
                from ACT_HI_VARINST WHERE ID_ = 'be9447b2-597c-11ef-9071-04421a8f2fce'
                """;

        HistoricVariableInstanceEntity varEntity = jdbcTemplate.queryForObject(sql, rowMapper);
        System.out.println(varEntity);
        byte[] commentData = readFileToByteArray("comment_data");


        varEntity.setByteArrayValue(commentData);
        varEntity.getTypedValue();

        return "success";
    }


    public static byte[] readFileToByteArray(String filePath) throws IOException {
        File file = new File(filePath);
        byte[] fileBytes = new byte[(int) file.length()];
        try (FileInputStream fis = new FileInputStream(file)) {
            int bytesRead = fis.read(fileBytes);
            if (bytesRead != fileBytes.length) {
                throw new IOException("Could not completely read the file " + file.getName());
            }
        }
        return fileBytes;
    }


    @GetMapping("/testInstant")
    public JSONObject testInstant() {
        JSONObject res = new JSONObject();
        res.put("date", Instant.now());
        return res;
    }



}
